<template>
  <!-- <div class="hello"> -->
  <div class="hello">
    <mt-field label="发票代码" placeholder="请输入10位或12位的发票代码" v-model="invoiceCode"></mt-field>
    <mt-field label="发票号码" placeholder="请输入8位的发票号码" v-model="invoiceNumber"></mt-field>
    <mt-field label="开票日期" placeholder="请输入开票日期" :readonly="readonly" v-model="invoiceDate"  @focus.native.capture="openPicker"></mt-field>

    <mt-field label="销售方名称" placeholder="请输入销售方名称" v-if="type=='T1'" v-model="invoiceSellor"></mt-field>
    <mt-field label="纳税人识别号" placeholder="请输入纳税人识别号" v-if="type=='T1'" v-model="invoiceTaxpayer"></mt-field>
    <mt-field label="上传发票" placeholder="" v-if="type=='T1'">
      <input class="upLoad" type="file" value=""  id="file"  @change='onUpload($event)' ref="file">
    </mt-field>
    <div v-if="type=='T1'" v-for='(item,index) in invoiceService' :key="index">
      <div class="setviceBox">
        <mt-badge size="small" type="error" @click.native="deleteService(index)">×</mt-badge>
        <mt-field label="服务内容" placeholder="" v-model="item.invoiceServiceContent"></mt-field>
        <mt-field label="服务金额" placeholder="" v-model="item.invoiceServiceAccount"></mt-field>
      </div>
    </div>
    

    <mt-field label="校验码"  v-show="type!='T1'" placeholder="请输入20位的校验码" v-if="numberInvoiceCheckCodeShow" v-model="invoiceCheckCode"></mt-field>
    <mt-field label="金额(不含税)" placeholder="请输入合计金额" type="number" v-if="!numberInvoiceCheckCodeShow" v-model="invoiceSum"></mt-field>

    <mt-button @click="addService" v-if="type=='T1'" class="addServce" type="primary" size="small"><span style="font-size:22px;line-height:25px">+</span><span style="font-size:14px;margin-left:5px;float:right;margin-top:3px;">新增服务内容</span></mt-button>

    <mt-field label="摘要"  v-if="type!='T1'" placeholder="输入发票事宜或标记，选填" v-model="invoicedigest"></mt-field>
    <mt-button class="discernBtn" v-if="type!='T1'" type="primary" @click="discernClick" size="large">识别</mt-button>
    <mt-button class="discernBtn" v-if="type=='T1'" type="primary" @click="commonClick" size="large">上传</mt-button>
    
      <mt-datetime-picker
        ref="picker"   
        type="date"
        :endDate="endDate"
        @confirm="handleConfirm" 
        v-model="dateVal">
      </mt-datetime-picker>
  </div>
</template>

<script>
  import axios from 'axios'
  import { Field, Toast } from 'mint-ui';
	import Bus from '@/bus.js'
  import toCapitalizationAmount from '@/toCapitalizationAmount.js'
  import qs from 'qs'

  export default {
    data () {
      return {
          invoiceService:[{
            invoiceServiceContent:'',
            invoiceServiceAccount:''
          }],
          invoiceCode: '',
          invoiceNumber: '',
          invoiceDate: '',
          dateVal: '',
          invoiceCheckCode: '',
          invoiceSum: '',
          invoicedigest: '',
          invoiceSellor:'',
          invoiceTaxpayer:'',
          invoiceDataVal:{},
          numberInvoiceCheckCodeShow:false,
          userId:'',
          type:'',
          readonly:true,
          endDate:new Date(),
          filesList: {
            annexName:'',
            originalName:'',
            annexUrl:''
          }
      }
    },
    beforeDestroy () {
        Bus.$emit('invoiceDataVal',this.invoiceDataVal);
        Bus.$emit('invoicedigest',this.invoicedigest);
    },
    created(){
      this.userId = this.$route.params.userId;
      this.type = this.$route.params.type;
      if(this.type == '01'){
        this.numberInvoiceCheckCodeShow = false;
        this.invoiceCheckCode = '0';
      }else{
        this.numberInvoiceCheckCodeShow = true;
        this.invoiceSum = '0';
      }
    },
    methods:{
        commonClick() { // 通用机的上传
          if(this.invoiceCode == ''||this.invoiceCode.length<10||this.invoiceCode.length>12){
            alert('请输入10位或12位的发票代码');
            return;
          }else if(this.invoiceNumber.length!=8){
            alert('请输入8位的发票号码');
            return;
          }else if(this.invoiceDate == ''){
            alert('请填入开票日期');
            return;
          }else if(this.invoiceSellor == ''){
            alert('请填入销售方名称');
            return;
          }else if(this.invoiceTaxpayer == ''){
            alert('请填入纳税人识别号');
            return;
          };
          for( let i of this.invoiceService){
            if(i.invoiceServiceContent == ''){
              alert('请输入服务内容')
              return;
            }else if(i.invoiceServiceAccount == ''){
              alert('请输入服务金额')
              return;
            }
          };
          let arr = []; //用来装服务内容和金额
          let money = 0;
          this.invoiceService.forEach((item,index)=>{
            const singleObj = { "apiType":"","cph":"","createAt":"","amount":item.invoiceServiceAccount,"detailNo":"","itemName": item.invoiceServiceContent,"goodsNum":"","id": '',"jxfpInvoices":null,"lx":"","num":"1","removeStatus":"","specificationModel":"","taxAmount":"","taxDetailAmount":"","taxRate":"0%","taxUnitPrice":"","txrqq":"","txrqz":"","unit":"","price":item.invoiceServiceAccount,"updateAt":null};
              arr.push(singleObj);
              money +=  item.invoiceServiceAccount-0;
          })

          let dataList = {
            "saleName": this.invoiceSellor, // 销售方
            "uploadIdentify": false,
            "unitError": false,
            "oilError": false,
            "buyerNameError": false,
            "repeatError": false,
            "noExistError": false,
            "tipWordShow": false,
            "tipWord": "",
            "ifInvoice": true,
            "foldB": true,
            "totalAmountLower": money, // 服务金额总数
            "showImg": [{annexName: this.filesList.annexName, originalName: this.filesList.annexName,annexUrl: this.filesList.annexUrl}],// 上传的发票
            "annexName" : this.filesList.annexName, // 文件名
            "billingDate": this.invoiceDate, // 开票日期
            "buyAdressPhone": "",
            "buyBankAccount": "",
            "buyIdentificationNum": "911201057303452110",
            "buyName": "天津中审联有限责任会计师事务所",
            "checkCode": "",
            "code": this.invoiceCode, // 代码 
            "id": "",
            "machineInvoiceId": "",
            "machineCode": "",
            "number": this.invoiceNumber, // 号码
            "reimMachineInvoiceRow": arr, // 服务内容
            "saleAdressPhone": "",
            "saleBankAccount": "",
            "saleIdentificationNum": this.invoiceTaxpayer, // 纳税人识别号
            "saleRemark": "",
            "totalAmountUpper": toCapitalizationAmount(money),
            "invoiceType": "T1"
          }
          let self = this;
          var qs = require('qs');
          axios.post('/wechatInvoice/invoice/saveT1Invoice.do', qs.stringify({"data": JSON.stringify({
            userId:this.userId,
            reimMachineInvoice:dataList,
          })}), {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' 
            }
          }).then(function (rep) {
            if (rep.data.status === '1') {
              Toast({
                message: '上传成功',
                iconClass: 'icon icon-success',
                duration: 1000
              });
              self.invoiceDataVal = rep.data.invoiceData;
              self.$router.push({path:'/InvoiceIdentification/upload/'+self.userId});
              // self.$router.push({path:'/HelloWorld/2/'+self.userId});
            }else{
            }
          }).catch(function(res){
            alert('失败'+JSON.stringify(res));
          });
          
        },
        onUpload(el) {
          let self = this;
          let myfile = self.$refs.file;
          if (myfile.length > 0) {
            let files = new FormData();
            files.append('file',myfile[0]);
            this.instance.post('wechatInvoice/invoice/fileUpload.do',files).then(function(res){
              self.filesList.annexName = res.data.data.fileName;
              self.filesList.originalName = res.data.data.name;
              self.filesList.annexUrl = res.data.data.annexUrl;
            })
          }
        },
        deleteService (index) {
          if(this.invoiceService.length>1){
            this.invoiceService.splice(index,1)
          }
        },
        addService() {
          this.invoiceService.push({
            invoiceServiceContent:'',
            invoiceServiceAccount:''
          })
        },
        openPicker() {
          if(this.invoiceDate == ''){
            const y = new Date().getFullYear()
            let m = new Date().getMonth() + 1
            m = m < 10 ? '0' + m : m
            let d = new Date().getDate()
            d = d < 10 ? ('0' + d) : d
            this.invoiceDate = y + '-' + m + '-' + d;
            this.invoiceDateVal =  String(y)+String(m)+String(d);
            this.dateVal = new Date();
          }else{
            this.dateVal = this.invoiceDate;
          }
          this.$refs.picker.open();
          return false;
        },
        handleConfirm(){ 
            const y = this.dateVal.getFullYear()
            let m = this.dateVal.getMonth() + 1
            m = m < 10 ? '0' + m : m
            let d = this.dateVal.getDate()
            d = d < 10 ? ('0' + d) : d
            this.invoiceDate = y + '-' + m + '-' + d;
            // this.invoiceDateVal = y+m+d;
            this.invoiceDateVal =  String(y)+String(m)+String(d);
        },
        discernClick(){
          if(this.invoiceCode == ''||this.invoiceCode.length<10||this.invoiceCode.length>12){
            alert('请输入10位或12位的发票代码');
          }else if(this.invoiceNumber.length!=8){
            alert('请输入8位的发票号码');
          }else if(this.invoiceDate == ''){
            alert('请填入开票日期');
          }else if(this.invoiceCheckCode.length != 6&&this.invoiceCheckCode.length != 20 && this.numberInvoiceCheckCodeShow == true){
            alert('请输入校验码或输入后6位');
          }else if(this.invoiceSum == ''){
            alert('请输入不含税的合计金额');
          }else{
            let invoiceContentVal = "01,"+this.type+","+this.invoiceCode+","+this.invoiceNumber+","+this.invoiceSum+","+this.invoiceDateVal+","+this.invoiceCheckCode+",,"
              var self = this;
              axios({
                headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
                method: 'get',
                url: '/wechatInvoice/invoice/rec.do',
                params: {
                  data: (() => {
                    let obj = {
                      invoiceContent:invoiceContentVal
                    }
                    Object.assign(obj, this.searchObj)
                    return JSON.stringify(obj);
                  })()
                }
              }).then((rep) => {
                if (rep.data.status === '1') {
                  self.invoiceDataVal = rep.data.invoiceData;
                  self.$router.push({path:'/InvoiceIdentification/upload/'+self.userId});
                }else{
                  alert(rep.data.msg);
                }
              }, (rep) => { });
          }
        },
    },
  };
</script>

<style lang="less" scoped>
.hello{
  // height: 100%;
}
.mu-demo-form {
  width: 100%;
  max-width: 460px;
}
.discernBtn{
  width: 80%;
  margin: 20px auto 0 auto;
  // margin-top: 20px;
}
.addServce{
  float: left;
  margin: 20px 0 60px 20px;
  height: 30px;
  width: 130px;
  background: #EFF4F7;
  color: #5EA4E6
}
.setviceBox{
  position: relative;
  .mint-badge{
    position:absolute;
    z-index: 10;
    right:20px;
    top: 40px;
    font-size: 13px
  }
}
</style>
